package servlets;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import entity.User;
import utils.DBUtils;
import utils.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/loginToken")
public class LoginTokenServlet extends HttpServlet {
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handleCors(resp);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        // 读取请求体中的JSON数据
        StringBuilder jsonBuilder = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }
        } catch (IOException e) {
            sendErrorResponse(resp, HttpServletResponse.SC_BAD_REQUEST, "无法读取请求数据");
            return;
        }

        // 解析JSON数据
        Map<String, String> loginData;
        try {
            loginData = gson.fromJson(jsonBuilder.toString(), Map.class);
        } catch (Exception e) {
            sendErrorResponse(resp, HttpServletResponse.SC_BAD_REQUEST, "无效的JSON格式");
            return;
        }

        // 验证必需字段
        if (loginData == null || !loginData.containsKey("username") || !loginData.containsKey("password")) {
            sendErrorResponse(resp, HttpServletResponse.SC_BAD_REQUEST, "必须提供用户名和密码");
            return;
        }

        String username = loginData.get("username");
        String password = loginData.get("password");

        // 验证用户名和密码不为空
        if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
            sendErrorResponse(resp, HttpServletResponse.SC_BAD_REQUEST, "用户名和密码不能为空");
            return;
        }

        // 数据库验证
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtils.getConnection();
            String sql = "SELECT * FROM t_dormuser WHERE userName = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                // 用户存在，验证密码
                String dbPassword = rs.getString("password");

                if (password.equals(dbPassword)) {
                    // 密码正确，生成Token
                    String token = JwtUtils.generateToken(username);

                    // 获取用户信息
                    User user = new User(
                            rs.getInt("dormManId"),
                            rs.getString("userName"),
                            null // 不返回密码
                    );
                    user.setDormBuildId(rs.getInt("dormBuildId"));

                    // 构建响应
                    JsonObject responseJson = new JsonObject();
                    responseJson.addProperty("code", 200);
                    responseJson.addProperty("message", "登录成功");
                    responseJson.addProperty("token", token);
                    responseJson.addProperty("username", username);
                    responseJson.add("user", gson.toJsonTree(user));

                    resp.getWriter().write(responseJson.toString());
                } else {
                    // 密码错误
                    sendErrorResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, "用户名或密码错误");
                }
            } else {
                // 用户不存在
                sendErrorResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, "用户名或密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            sendErrorResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器错误: " + e.getMessage());
        } finally {
            DBUtils.close(conn, pstmt, rs);
        }
    }

    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        handleCors(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }

    private void handleCors(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Custom-Header");
    }

    private void sendErrorResponse(HttpServletResponse resp, int statusCode, String message) throws IOException {
        resp.setStatus(statusCode);
        JsonObject errorJson = new JsonObject();
        errorJson.addProperty("code", statusCode);
        errorJson.addProperty("message", message);
        resp.getWriter().write(errorJson.toString());
    }
}